//
//  DropDownChooseView.m
//  DropdownChooseDemo
//
//  Created by Felix on 14-3-17.
//  Copyright (c) 2014年 xxyyzz. All rights reserved.
//

#import "DropDownChooseView.h"

@implementation DropDownChooseView
@synthesize chooseDataSource;
@synthesize chooseDelegate;
@synthesize mTableView,mTableBaseView;
@synthesize mSuperView;

-(id)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self) {

    }
    return self;
}

- (id)initWithFrame:(CGRect)frame dataSource:(id)dataSource delegate:(id)delegate
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
        
        self.backgroundColor = [UIColor lightGrayColor];
        
        currentExtendSection = -1;//当前打开的section，默认为-1，表示没有点开哪个section
        
        self.chooseDataSource = dataSource;
        self.chooseDelegate = delegate;
        
        NSInteger sectionNum = 0;
        if([chooseDataSource respondsToSelector:@selector(numberOfSections)]){
            sectionNum = [chooseDataSource numberOfSections];
        }
        
        if(sectionNum == 0){
            self = nil;
        }
        
        //初始化默认显示View
        CGFloat sectionWith = (1.0*(frame.size.width)/sectionNum);
        for (int i=0; i<sectionNum; i++) {
            UIButton *sectionBtn = [[UIButton alloc]initWithFrame:CGRectMake(sectionWith*i, 1, sectionWith, frame.size.height - 2)];
            sectionBtn.tag = SECTION_BTN_TAG_BEGIN + i;
            [sectionBtn addTarget:self action:@selector(sectionBtnAction:) forControlEvents:UIControlEventTouchUpInside];
            NSString *sectionBtnTitle = @"--";
            if([chooseDataSource respondsToSelector:@selector(titleInSection:index:)]){
                sectionBtnTitle = [chooseDataSource titleInSection:i index:[chooseDataSource defaultShowIndexInSection:i]];
            }
            [sectionBtn setTitle:sectionBtnTitle forState:UIControlStateNormal];
            [sectionBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
            sectionBtn.titleLabel.font = [UIFont boldSystemFontOfSize:14.0f];
            [self addSubview:sectionBtn];
            
            UIImageView *sectionBtnIv = [[UIImageView alloc]initWithFrame:CGRectMake(sectionWith*i + (sectionWith - 16), (frame.size.height - 12)/2, 12, 12)];
            [sectionBtnIv setImage:[UIImage imageNamed:@"down_dark.png"]];
            [sectionBtnIv setContentMode:UIViewContentModeScaleAspectFit];
            sectionBtnIv.tag = SECTION_IV_TAG_BEGIN + i;
            [sectionBtn setBackgroundColor: [UIColor whiteColor]];
            [self addSubview:sectionBtnIv];
            
            if(i < sectionNum){
                UIView *lineView = [[UIView alloc]initWithFrame:CGRectMake(sectionWith*i , frame.size.height/4, 1, frame.size.height/2)];
                lineView.backgroundColor = [UIColor lightGrayColor];
                [self addSubview:lineView];
            }
            
        }
        
    }
    return self;
}

-(void)recoverAllSectionBtnStatus{
    for (UIView *tempView in [self subviews]) {
        if(tempView.tag >= SECTION_BTN_TAG_BEGIN && [tempView isKindOfClass:[UIButton class]]){
            [((UIButton *)tempView) setTitleColor:[UIColor darkGrayColor] forState:UIControlStateNormal];
        }
        
        if(tempView.tag >= SECTION_IV_TAG_BEGIN && [tempView isKindOfClass:[UIImageView class]]){
            [((UIImageView *)tempView) setImage:[UIImage imageNamed:@"down_dark.png"]];
        }
    }
}

-(void)sectionBtnAction:(UIButton *)btn{
    NSInteger section = btn.tag - SECTION_BTN_TAG_BEGIN;
    
    if(currentExtendSection == section){
        //disappear section view
        [self hideExtendedChooseView];
        
    }else{
        //disappear section old view
        currentExtendSection = section;
        
        [self recoverAllSectionBtnStatus];
        [btn setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
        UIImageView *currentIv = (UIImageView *)[self viewWithTag:(3000 + section)];
        [currentIv setImage:[UIImage imageNamed:@"up_light.png"]];
        
        //show new section view
        [self showChooseListViewInSection:currentExtendSection choosedIndex:[chooseDataSource defaultShowIndexInSection:currentExtendSection]];
    }
}

-(void)hideExtendedChooseView{
    
    [self recoverAllSectionBtnStatus];
    
    if(currentExtendSection != -1){
        currentExtendSection = -1;
        [UIView animateWithDuration:0.5 animations:^(void){
            self.mTableBaseView.alpha = 1.0;
            self.mTableView.alpha = 1.0;
            
            self.mTableBaseView.alpha = 0.2;
            self.mTableView.alpha = 0.2;
            
        } completion:^(BOOL finished){
            
            [self.mTableView removeFromSuperview];
            [self.mTableBaseView removeFromSuperview];
        }];
    }
}

-(void)showChooseListViewInSection:(NSInteger)section choosedIndex:(NSInteger)index{
    if(!mTableView){
        self.mTableBaseView = [[UIView alloc]initWithFrame:CGRectMake(self.frame.origin.x, self.frame.origin.y + self.frame.size.height, self.frame.size.width, mSuperView.frame.size.height - self.frame.origin.y - self.frame.size.height)];
        self.mTableBaseView.backgroundColor = [UIColor colorWithWhite:0.0f alpha:0.5];
        
        UITapGestureRecognizer *bgTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(bgTappedAction:)];
        [self.mTableBaseView addGestureRecognizer:bgTap];
        
        self.mTableView = [[UITableView alloc]initWithFrame:CGRectMake(self.frame.origin.x, self.frame.origin.y + self.frame.size.height, self.frame.size.width, 240) style:UITableViewStylePlain];
        self.mTableView.delegate = self;
        self.mTableView.dataSource = self;
    }
    [mSuperView addSubview:self.mTableBaseView];
    [mSuperView addSubview:mTableView];
    
    [UIView animateWithDuration:0.5 animations:^(void){
        self.mTableBaseView.alpha = 0.2;
        self.mTableView.alpha = 0.2;
        
        self.mTableBaseView.alpha = 1.0;
        self.mTableView.alpha = 1.0;
    }];
    
    [self.mTableView reloadData];
}

-(void)bgTappedAction:(UITapGestureRecognizer *)tap{
    [self hideExtendedChooseView];
}

#pragma mark - list tableView degate
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return [chooseDataSource numberOfRowsInSection:currentExtendSection];
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 40.0f;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSString *cellIdentifier = @"cellIdentifier";
    UITableViewCell *mCell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if(!mCell){
        mCell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
        mCell.accessoryType = UITableViewCellAccessoryNone;
    }
    
    mCell.textLabel.text = [chooseDataSource titleInSection:currentExtendSection index:indexPath.row];
    mCell.textLabel.font = [UIFont systemFontOfSize:14.0f];
    
    return mCell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if([chooseDelegate respondsToSelector:@selector(choosedAtSection:index:)]){
        
        NSString *choosedCellTitle = [chooseDataSource titleInSection:currentExtendSection index:indexPath.row];
        
        UIButton *currentSectionBtn = (UIButton *)[self viewWithTag:1000 + currentExtendSection];
        [currentSectionBtn setTitle:choosedCellTitle forState:UIControlStateNormal];
        
        
        [chooseDelegate choosedAtSection:currentExtendSection index:indexPath.row];
        
        [self hideExtendedChooseView];
    }
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
    // Drawing code
}
*/

@end
